package com.example.demo;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

public class PhotoTransfer {

    private static final Logger LOGGER = Logger.getLogger(PhotoTransfer.class.getName());

    private static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/pyd-tobacco-collection?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true"; // 替换为你的数据库URL
    private static final String DB_USER = "root"; // 替换为你的数据库用户名
    private static final String DB_PASSWORD = "1234"; // 替换为你的数据库密码
    private static final String SOURCE_DIR = "D:/modalData";
    private static final String DESTINATION_DIR = "E:\\2025.06.21\\modalData\\sampledata";

    public static void main(String[] args) {
        List<String> imageUrls = getImageUrlsFromDatabase();

        if (imageUrls != null && !imageUrls.isEmpty()) {
            transferAndCropPhotos(imageUrls);
        } else {
            LOGGER.info("数据库中没有找到图片 URL。");
        }
    }

    /**
     * 从数据库中获取图片URL列表.
     * @return 图片URL列表, 如果发生错误则返回 null.
     */
    private static List<String> getImageUrlsFromDatabase() {
        List<String> imageUrls = new ArrayList<>();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // 1. 注册 JDBC 驱动
            Class.forName("com.mysql.cj.jdbc.Driver"); // 替换为你的 JDBC 驱动类名

            // 2. 建立数据库连接
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            LOGGER.info("成功连接到数据库。");

            // 3. 创建 Statement 对象
            stmt = conn.createStatement();

            // 4. 执行 SQL 查询
            String sql = "SELECT industrial_camera_image_url,  near_infrared_camera_image_url FROM sample_data where del_flag=0"; // 替换为你的表名
            rs = stmt.executeQuery(sql);
            LOGGER.info("成功执行 SQL 查询。");

            // 5. 处理查询结果
            while (rs.next()) {
                // 获取所有列的图片URL
                String industrialCameraImageUrl = rs.getString("industrial_camera_image_url");

                String nearInfraredCameraImageUrl = rs.getString("near_infrared_camera_image_url");

                // 将非空的URL添加到列表中
                if (industrialCameraImageUrl != null && !industrialCameraImageUrl.isEmpty()) {
                    imageUrls.add(industrialCameraImageUrl);
                }

                if (nearInfraredCameraImageUrl != null && !nearInfraredCameraImageUrl.isEmpty()) {
                    imageUrls.add(nearInfraredCameraImageUrl);
                }
            }
            LOGGER.info("从数据库中获取了 " + imageUrls.size() + " 个图片 URL。");

        } catch (ClassNotFoundException e) {
            LOGGER.log(Level.SEVERE, "JDBC 驱动未找到: " + e.getMessage(), e);
            return null;
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "数据库连接失败或查询错误: " + e.getMessage(), e);
            return null;
        } finally {
            // 6. 关闭连接 (重要!)
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
                LOGGER.info("成功关闭数据库连接。");
            } catch (SQLException e) {
                LOGGER.log(Level.SEVERE, "关闭数据库连接失败: " + e.getMessage(), e);
            }
        }

        return imageUrls;
    }

    /**
     * 将图片从源目录转移到目标目录并进行裁剪.
     * @param imageUrls 图片URL列表.
     */
    private static void transferAndCropPhotos(List<String> imageUrls) {
        for (String imageUrl : imageUrls) {
            String sourceFilePath = SOURCE_DIR + "/" + imageUrl;
            File sourceFile = new File(sourceFilePath);

            if (sourceFile.exists() && sourceFile.isFile()) {
                try {
                    BufferedImage originalImage = ImageIO.read(sourceFile);
                    BufferedImage croppedImage = cropImage(originalImage);

                    if (croppedImage != null) {
                        String destinationFilePath = DESTINATION_DIR + "/" + imageUrl;
                        File destinationFile = new File(destinationFilePath);

                        File destinationDir = destinationFile.getParentFile();
                        if (!destinationDir.exists()) {
                            if (!destinationDir.mkdirs()) {
                                LOGGER.log(Level.SEVERE, "创建目标目录失败: " + destinationDir.getAbsolutePath());
                                continue;
                            }
                            LOGGER.log(Level.INFO, "已创建目标目录: " + destinationDir.getAbsolutePath());
                        }

                        String fileExtension = getFileExtension(sourceFile.getName());
                        ImageIO.write(croppedImage, fileExtension, destinationFile);
                        LOGGER.log(Level.INFO, "已传输并裁剪: " + imageUrl + " 到 " + destinationFilePath);
                    } else {
                        LOGGER.log(Level.WARNING, "裁剪图片失败: " + imageUrl);
                    }

                } catch (IOException e) {
                    LOGGER.log(Level.SEVERE, "处理 " + imageUrl + " 失败: " + e.getMessage(), e);
                } catch (Exception e) {
                    LOGGER.log(Level.SEVERE, "处理 " + imageUrl + " 时发生意外错误: " + e.getMessage(), e);
                }
            } else {
                LOGGER.log(Level.WARNING, "未找到源文件: " + sourceFilePath);
            }
        }
    }

    /**
     * 裁剪图片.
     * @param originalImage 原始图片.
     * @return 裁剪后的图片, 如果发生错误则返回 null.
     */
    private static BufferedImage cropImage(BufferedImage originalImage) {
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();

        if (width == 5120 && height == 5120) {
            // 从中间裁剪成 3840x2880
            int cropWidth = 3840;
            int cropHeight = 2880;
            int startX = (width - cropWidth) / 2;
            int startY = (height - cropHeight) / 2;
            return originalImage.getSubimage(startX, startY, cropWidth, cropHeight);
        } else if (width == 2592 && height == 2048) {
            // 裁剪成 1960x1440, 重心为 0.4984:0.4736
            int cropWidth = 1960;
            int cropHeight = 1440;
            double centerXRatio = 0.4984;
            double centerYRatio = 0.4736;

            int startX = (int) (width * centerXRatio - cropWidth / 2);
            int startY = (int) (height * centerYRatio - cropHeight / 2);

            // 确保裁剪区域在图片范围内
            startX = Math.max(0, Math.min(startX, width - cropWidth));
            startY = Math.max(0, Math.min(startY, height - cropHeight));

            return originalImage.getSubimage(startX, startY, cropWidth, cropHeight);
        } else {
            LOGGER.info("图片尺寸不支持裁剪: " + width + "x" + height);
            return null; // 不支持的尺寸，不裁剪
        }
    }

    /**
     * 获取文件的扩展名.
     * @param filename 文件名.
     * @return 文件的扩展名 (小写).
     */
    private static String getFileExtension(String filename) {
        int dotIndex = filename.lastIndexOf(".");
        if (dotIndex > 0 && dotIndex < filename.length() - 1) {
            return filename.substring(dotIndex + 1).toLowerCase();
        } else {
            return "jpg"; // 默认返回 jpg
        }
    }
}
